//
//  GYMineProductInfoEditViewModel.m
//  GYDemo
//
//  Created by mac on 2018/3/30.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "GYMineProductInfoEditViewModel.h"
#import "Head.h"

@implementation GYMineProductInfoEditDetailCellModel
-(NSString *)cellHeights
{
    if (!_cellHeights) {
        _cellHeights = [NSString stringWithFormat:@"%.f",WFCGFloatY(45)];
    }
    return _cellHeights;
}
@end

@interface GYMineProductInfoEditUpdateModel()
@property (nonatomic,strong) NSDictionary *titleInfo;
@end

@implementation GYMineProductInfoEditUpdateModel
#pragma mark - getter and setter
-(NSMutableDictionary *)otherInfo
{
    if (!_otherInfo) {
        _otherInfo = [NSMutableDictionary new];
    }
    return _otherInfo;
}
#pragma mark - method
-(NSMutableDictionary *)exportParameter
{
    NSMutableDictionary *para = [[NSMutableDictionary alloc]initWithDictionary:self.otherInfo];
    for (NSString *key in mustFillKeys) {
        NSString *value = [self valueForKey:key] ?: @"";
        if (!value || value.length <= 0) {
            NSLog(@"必选项校验");
            NSLog(@"key : %@ value : %@ class: %@",key,value,NSStringFromClass(value.class));
            para = nil;
            NSString *title = _titleInfo[key];
            if (title) {
                NSString *msg = [NSString stringWithFormat:@"请完善 %@ 信息！",title];
                [FTIndicator showErrorWithMessage:msg];
            }
            
            break;
        }else{
            [para setObject:value forKey:key];
        }
    }
    if (_idField) {
        [para setObject:_idField forKey:@"id"];
    }
    if (_descriptionField) {
        [para setObject:_descriptionField forKey:@"description"];
    }
    
    return para;
}

-(BOOL)isContainKey:(NSString *)key
{
    return [allKeys containsObject:key ?: @""];
}

-(void)setValue:(id)value forKey:(NSString *)key
{
    if ([self isContainKey:key]) {
        [super setValue:value forKey:key];
    }else{
        [self.otherInfo setValue:value forKey:key];
    }
}

-(instancetype)init
{
    if (self = [super init]) {
         [[InterfaceManager shareInterface].specialInterfaces addObject:@"productTypeProperty"];
        mustFillKeys = @[@"name",@"protypeid",@"unit",@"count",@"setnum",@"province",@"city",@"area",@"price",@"imgUrl"];
        allKeys = @[@"name",@"protypeid",@"unit",@"count",@"setnum",@"province",@"city",@"area",@"price",@"imgUrl",@"idField",@"descriptionField",@"otherInfo"];
        _titleInfo = @{
                       @"name":@"品类",
                       @"protypeid":@"种类",
                       @"province":@"地区",
                       @"city":@"地区",
                       @"area":@"地区",
                       @"unit":@"种类",
                       @"price":@"价格",
                       @"count":@"数量",
                       @"setnum":@"起订数量",
                       @"imgUrl":@"产品图片"
                       };
    }
    return self;
}
@end

@interface GYMineProductInfoEditViewModel()
@property (nonatomic,assign) BOOL isUpdate;
@property (nonatomic,strong) NSMutableArray *detailNormalItems;
@property (nonatomic,strong) NSMutableArray *detailSpecialItems;
@property (nonatomic,strong) NSMutableArray *detailNormalItems2;
@end

@implementation GYMineProductInfoEditViewModel
#pragma mark - getter and setter
-(BOOL)isUpdate
{
    _isUpdate = _productInfoDetailModel ? YES : NO;
    return _isUpdate;
}
-(NSMutableArray *)detailItems
{
    if (!_detailItems) {
        _detailItems = [NSMutableArray new];
    }
    [_detailItems removeAllObjects];
    [_detailItems addObject:self.detailNormalItems];
    !self.detailSpecialItems ?: [_detailItems addObject:self.detailSpecialItems];
    [_detailItems addObject:self.detailNormalItems2];
    return _detailItems;
}

-(NSMutableArray *)detailNormalItems
{
    if (!_detailNormalItems) {
        _detailNormalItems = [NSMutableArray new];
        GYMineProductInfoEditDetailCellModel *cellmodel1 = [GYMineProductInfoEditDetailCellModel new];
        cellmodel1.title = @"品类";
        cellmodel1.key = @"name";
        cellmodel1.value = self.productInfoDetailModel.name;
        cellmodel1.inputType = UIKeyboardTypeDefault;
        
        GYMineProductInfoEditDetailCellModel *cellmodel2 = [GYMineProductInfoEditDetailCellModel new];
        cellmodel2.title = @"种类";
        cellmodel2.key = @"catogery";
        cellmodel2.value = self.productInfoDetailModel.protypename;
        cellmodel2.action = @"chooseCatogery:";
        
        GYMineProductInfoEditDetailCellModel *cellmodel3 = [GYMineProductInfoEditDetailCellModel new];
        cellmodel3.title = @"数量";
        cellmodel3.key = @"count";
        cellmodel3.value = self.productInfoDetailModel.count > 0 ? [NSString stringWithFormat:@"%ld",self.productInfoDetailModel.count] : @"";
        cellmodel3.inputType = UIKeyboardTypeNumberPad;
        
        GYMineProductInfoEditDetailCellModel *cellmodel4 = [GYMineProductInfoEditDetailCellModel new];
        cellmodel4.title = @"起订数量";
        cellmodel4.key = @"setnum";
        cellmodel4.value = self.productInfoDetailModel.setnum > 0 ? [NSString stringWithFormat:@"%ld",self.productInfoDetailModel.setnum] : @"";
        cellmodel4.inputType = UIKeyboardTypeNumberPad;
        
        GYMineBuyInfoEditDetailCellModel *cellmodel41 = [GYMineProductInfoEditDetailCellModel new];
        cellmodel41.title = @"地区";
        cellmodel41.key = @"area";
        cellmodel41.value = self.productInfoDetailModel.address;
        cellmodel41.action = @"chooseArea:";
        
        GYMineProductInfoEditDetailCellModel *cellmodel5 = [GYMineProductInfoEditDetailCellModel new];
        cellmodel5.title = @"价格";
        cellmodel5.key = @"price";
        cellmodel5.value = self.productInfoDetailModel.price > 0 ? [NSString stringWithFormat:@"%.2ld",self.productInfoDetailModel.price] : @"";
        cellmodel5.action = @"inputPrice:";
        
//        GYMineProductInfoEditDetailCellModel *cellmodel6 = [GYMineProductInfoEditDetailCellModel new];
//        cellmodel6.title = @"图片";
//        cellmodel6.key = @"imgUrl";
////        cellmodel6.value = ;
//        cellmodel6.imgUrl = [NSString stringWithFormat:@"%@%@",self.productInfoDetailModel.imgUrl,kProductImgThumbnailSuffix];
//        cellmodel6.specialType = 1;
//        cellmodel6.action = @"chooseImage:";
//        cellmodel6.cellHeight = WFCGFloatY(113.5);
        
        GYMineProductInfoEditDetailCellModel *cellmodel6 = [GYMineProductInfoEditDetailCellModel new];
        cellmodel6.title = @"";
        cellmodel6.key = @"imgs";
        //        cellmodel6.value = ;
        NSMutableArray *imgs = [NSMutableArray new];
        for (NSDictionary *dic in self.productInfoDetailModel.imgUrl) {
            NSString *picurl = dic[@"picurl"] ?: @"";
            [imgs addObject:picurl];
        }
        cellmodel6.imgs = imgs;
        cellmodel6.specialType = 2;
        cellmodel6.cellHeights = [NSString stringWithFormat:@"%f",WFCGFloatY(127)];
        
        NSArray *items = @[
                           cellmodel1,
                           cellmodel2,
                           cellmodel3,
                           cellmodel4,
                           cellmodel41,
                           cellmodel5,
                           cellmodel6,
                           ];
        [_detailNormalItems addObjectsFromArray:items];
    }
    return _detailNormalItems;
}
-(NSMutableArray *)detailSpecialItems
{
    if (!_detailSpecialItems) {
        _detailSpecialItems = [NSMutableArray new];
    }
    return _detailSpecialItems;
}
-(NSMutableArray *)detailNormalItems2
{
    if (!_detailNormalItems2) {
        _detailNormalItems2 = [NSMutableArray new];
        GYMineProductInfoEditDetailCellModel *cellmodel1 = [GYMineProductInfoEditDetailCellModel new];
        cellmodel1.title = @"产品介绍";
        cellmodel1.key = @"";
        cellmodel1.action = @"";
        cellmodel1.cellHeight = WFCGFloatY(45);
        
        GYMineProductInfoEditDetailCellModel *cellmodel2 = [GYMineProductInfoEditDetailCellModel new];
        cellmodel2.title = @"";
        cellmodel2.key = @"descriptionField";
        cellmodel2.value = self.productInfoDetailModel.descriptionField;
        cellmodel2.inputType = UIKeyboardTypeDefault;
        cellmodel2.isExpandable = YES;
        cellmodel1.cellHeight = WFCGFloatY(45);
        NSArray *items = @[
                           cellmodel1,
                           cellmodel2
                           ];
        [_detailNormalItems2 addObjectsFromArray:items];
    }
    return _detailNormalItems2;
}
-(GYMineProductInfoEditUpdateModel *)updateModel
{
    if (!_updateModel) {
        _updateModel = [GYMineProductInfoEditUpdateModel new];
    }
    return _updateModel;
}

-(void)setProductInfoDetailModel:(GYMineProductInfoDetailModel *)productInfoDetailModel
{
    _productInfoDetailModel = productInfoDetailModel;
    self.updateModel.idField = [NSString stringWithFormat:@"%ld",_productInfoDetailModel.idField];
    _updateModel.name = _productInfoDetailModel.name;
    _updateModel.protypeid = [NSString stringWithFormat:@"%ld",_productInfoDetailModel.protypeid];
    _updateModel.province = _productInfoDetailModel.province;
    _updateModel.city = _productInfoDetailModel.city;
    _updateModel.area = _productInfoDetailModel.area;
    _updateModel.unit = _productInfoDetailModel.unit;
    _updateModel.price = [NSString stringWithFormat:@"%.2ld",(long)_productInfoDetailModel.price];
    _updateModel.count = [NSString stringWithFormat:@"%ld",_productInfoDetailModel.count];
    _updateModel.setnum = [NSString stringWithFormat:@"%ld",_productInfoDetailModel.setnum];
    _updateModel.descriptionField = _productInfoDetailModel.descriptionField;
    NSData *data;
    if (@available(iOS 11.0, *)) {
        data = [NSJSONSerialization dataWithJSONObject:_productInfoDetailModel.imgUrl ?: @[] options:NSJSONWritingPrettyPrinted | NSJSONWritingSortedKeys error:nil];
    } else {
        data = [NSJSONSerialization dataWithJSONObject:_productInfoDetailModel.imgUrl ?: @[] options:NSJSONWritingPrettyPrinted error:nil];
    }
    NSString *imgstr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    _updateModel.imgUrl = imgstr;
    
    //请求产品类型信息
    NSString *pid = [NSString stringWithFormat:@"%ld",_productInfoDetailModel.protypeid];
    NSMutableDictionary *para = [NSMutableDictionary new];
    [para setObject:pid forKey:@"id"];
    [self requestType:para];
}
#pragma mark - method
///更新求购信息详情
-(void)upadteproductInfoDetail
{
//    GYMineProductInfoDetailModel *detail = [_productInfoDetailModel yy_modelCopy];
    _productInfoDetailModel.name = _updateModel.name;
    _productInfoDetailModel.protypeid = _updateModel.protypeid.integerValue;
    _productInfoDetailModel.province = _updateModel.province;
    _productInfoDetailModel.city = _updateModel.city;
    _productInfoDetailModel.area = _updateModel.area;
    _productInfoDetailModel.unit = _updateModel.unit;
    _productInfoDetailModel.price = _updateModel.price.doubleValue;
    _productInfoDetailModel.count = _updateModel.count.integerValue;
    _productInfoDetailModel.descriptionField = _updateModel.descriptionField;
    NSData *data = [_updateModel.imgUrl dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *imgs = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments error:nil];
    _productInfoDetailModel.imgUrl = imgs;
    
    NSMutableArray *otherProperty = [[NSMutableArray alloc]initWithArray:_productInfoDetailModel.propertyList];
    for (NSInteger i = 0; i < otherProperty.count; i++) {
        NSDictionary *dic = otherProperty[i];
        NSMutableDictionary *mdic = [[NSMutableDictionary alloc]initWithDictionary:dic];
        NSString *key = [NSString stringWithFormat:@"%@",dic[@"propertyid"]];
        NSString *value = _updateModel.otherInfo[key] ?: @"";
        [mdic setValue:value forKey:@"propertyvalue"];
        [otherProperty replaceObjectAtIndex:i withObject:mdic];
        
    }
    NSLog(@"%@",otherProperty);
    _productInfoDetailModel.propertyList = otherProperty;
    [self setUpdateSign:@"Ture"];
}

-(NSDictionary *)propertyInfo:(NSString *)key
{
    NSDictionary *res = nil;
    NSArray *otherProperty = _productInfoDetailModel.propertyList;
    if ([otherProperty isKindOfClass:[NSArray class]]) {
        if (otherProperty.count > 0) {
            for (NSDictionary *dic in otherProperty) {
                NSString *propertyid = [NSString stringWithFormat:@"%@",dic[@"propertyid"]];
                if ([key isEqualToString:propertyid]) {
                    res = dic;
                    break;
                }
            }
        }
    }
    return res;
}

-(void)requestType:(NSMutableDictionary *)para
{
    @WeakSelf;
    NSString *interface = @"productTypeProperty";
    [[InterfaceManager shareInterface]requetInterface:interface withParameter:para handler:^(NSDictionary *info, InterfaceStatusModel *infoModel) {
        NSArray *data = (NSArray *)infoModel.data;
        if ([data isKindOfClass:[NSArray class]]) {
            NSMutableArray *marr = [NSMutableArray new];
            for (NSDictionary *dic in data) {
                if ([dic isKindOfClass:[NSDictionary class]]) {
                    GYMineBuyInfoDetailSpecialPropertyModel *property = [GYMineBuyInfoDetailSpecialPropertyModel yy_modelWithJSON:dic];
                    NSString *title = property.name;
                    NSInteger type = property.type;
                    NSString *key = [NSString stringWithFormat:@"%ld",property.idField];
                    GYMineProductInfoEditDetailCellModel *cellmodel;
                    if (2 == type) {
                        //选择类型
                        NSDictionary *data = @{@"data":property.list};
                        cellmodel = [[GYMineProductInfoEditDetailCellModel alloc]initWithTitle:title key:key action:@"otherProperty:" other:data];
                        NSDictionary *defaultpro = [selfp propertyInfo:key];
                        if (defaultpro) {
                            NSString *propertyvalue = defaultpro[@"propertyvalue"] ?: @"";
                            cellmodel.value = propertyvalue;
                            [selfp.updateModel.otherInfo setValue:cellmodel.value forKey:key];
                        }else{
                            if (property.list.count > 0) {
                                NSDictionary *dic = property.list[0];
                                if ([dic isKindOfClass:[NSDictionary class]]) {
                                    NSString *value = dic[@"provalue"];
                                    cellmodel.value = value;
                                    [selfp.updateModel.otherInfo setValue:cellmodel.value forKey:key];
                                }
                            }
                        }
                    } else {
                        //输入类型
                        cellmodel = [[GYMineProductInfoEditDetailCellModel alloc]initWithTitle:title key:key keyboardType:UIKeyboardTypeDefault];
                        NSDictionary *defaultpro = [selfp propertyInfo:key];
                        if (defaultpro) {
                            NSString *propertyvalue = defaultpro[@"propertyvalue"] ?: @"";
                            cellmodel.value = propertyvalue;
                            [selfp.updateModel.otherInfo setValue:cellmodel.value forKey:key];
                        }else{
                            cellmodel.value = @"";
                            [selfp.updateModel.otherInfo setValue:cellmodel.value forKey:key];
                        }
                    }
                    [marr addObject:cellmodel];
                }
            }
            [selfp setDetailSpecialItems:marr];
        }
    }];
}
-(void)requestSave
{
    @WeakSelf;
    NSString *interface = @"modifySaleProduct";
    if (self.isUpdate) {
        interface = @"modifySaleProduct";
    }else{
        interface = @"saveSaleProduct";
    }
    NSMutableDictionary *para = [self.updateModel exportParameter];
    if (para) {
        [[InterfaceManager shareInterface]requetInterface:interface withParameter:para handler:^(NSDictionary *info, InterfaceStatusModel *infoModel) {
            [FTIndicator showSuccessWithMessage:@"保存成功"];
            [selfp upadteproductInfoDetail];
        }];
    }
}

-(instancetype)init
{
    if (self = [super init]) {
        [[InterfaceManager shareInterface].specialInterfaces addObject:@"productTypeProperty"];
    }
    return self;
}
@end
